package com.gxd.dao.impl;

import com.gxd.dao.ShowGoodTypeDao;
import com.gxd.domain.GoodsType;
import com.gxd.util.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class ShowGoodTypeDaoImpl implements ShowGoodTypeDao {
    QueryRunner queryRunner = new QueryRunner(DBUtils.getDataSource());
    @Override
    public List<GoodsType> findGoodType() {
        String sql=" select id,name,level,Parent from tb_goods_type ";
        try {
            return queryRunner.query(sql,new BeanListHandler<>(GoodsType.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteById(int id) {
        String sql=" delete from tb_goods_type where id=? ";
        try {
            queryRunner.update(sql,id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void addGoodType(GoodsType goodsType) {
        String sql=" insert into tb_goods_type values(null,?,?,?) ";
        try {
            Object[] params={goodsType.getName(),goodsType.getLevel(),goodsType.getParent()};
            queryRunner.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public GoodsType selectLevel(int goodsParent) {
        String sql=" select id,name,level,Parent from tb_goods_type where id=? ";
        try {
            return  queryRunner.query(sql,new BeanHandler<>(GoodsType.class),goodsParent);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void update(GoodsType goodsType) {
        String sql=" update  tb_goods_type set name=?,level=?,parent=? where id=? ";
        try {
            Object[] params={goodsType.getName(),goodsType.getLevel(),goodsType.getParent(),goodsType.getId()};
            queryRunner.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public GoodsType findById(int id) {
        String sql=" select id,name,level,Parent from tb_goods_type  where id=? ";
        try {
            return queryRunner.query(sql,new BeanHandler<>(GoodsType.class),id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
